<?php


namespace app\admin\traits;

use app\common\utils\facade\FileUtil;
use app\common\utils\ImageUtil;
use think\Exception;
use think\facade\Filesystem;
use app\common\validate\Image as ImageValidate;
use think\facade\Log;

trait UploadImage
{
    /**
     * @param string $field
     * @param string $folder
     * @param array $size 剪切大小[width=>100, height=>100]
     * @return \think\response\Json
     */
    private function upload(string $field, string $folder, array $size=[]){
        if (!request()->isAjax()) abort(405, '请求方式不被允许');
        $folder = rtrim($folder,'/');

        try{
            $files = request()->file();
            if (empty($files)) throw new Exception('没有选择任何图片.');
            validate(ImageValidate::class)->check($files);


            if( !$savename = Filesystem::putFile( $folder, $files[$field]) )
                throw new Exception('上传失败.');
            //如果不剪切直接返回上传后的图片地址
            if(empty($size)){
                return json([
                    'code' => 0,
                    'msg'  => '上传成功.',
                    'data' => [
                        'src' => str_replace('\\','/', $savename)
                    ]
                ]);
            }

            $thumbFile = $this->thumbFile($savename, $folder, $size);

            return json([
                'code' => 0,
                'msg'  => '保存成功.',
                'data' => [
                    'src' => str_replace('\\','/', $thumbFile)
                ]
            ]);



        }catch (\Exception $e){
            Log::error($this->request->completePathInfo(true) . ' : ' .$e->getMessage());
            return json([
                'code' => 1,
                'msg'  => $e->getMessage(),
            ]);
        }


    }

    /**
     * 剪切图片
     * @param $fileName string 原图片
     * @param $folder string 子目录
     * @param $size array 剪切配置
     * @return string string 剪切后的图片相对目录
     * @throws Exception
     */
    private function thumbFile(string $fileName, string $folder, array $size){
        //剪切图片
        $rootPath = config('filesystem.disks.local.root') . '/';
        $oriFile  = $rootPath . $fileName;
        $savePath = $folder . '/' . date('Ymd', time()) . '/';

        $conf = [
            'file' => $oriFile,
            'path' => $rootPath . $savePath,
        ];
        if (empty($size['width']) && empty($size['height']))
            throw new Exception('配置失败.');
        //如果设置了宽或高
        if (!empty($size['width']))
            $conf['width'] = $size['width'];
        if (!empty($size['height']))
            $conf['height'] = $size['height'];

        $res = ImageUtil::thumb($conf);
        if(!$res){
            throw new Exception(ImageUtil::$error);
        }
        //删除原图片
        FileUtil::unlinkFile($oriFile);

        return $savePath . $res;
    }

}